package com.lmoumou.lib_pdfload.view

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Typeface
import android.util.AttributeSet
import android.widget.ProgressBar
import com.lmoumou.lib_pdfload.R

/**
 * @author Lmoumou
 * @date : 2019/8/27 15:55
 */
class NumberProgressBar(context: Context, attrs: AttributeSet, defStyleAttr: Int) :
    ProgressBar(context, attrs, defStyleAttr) {
    /**
     * 画笔对象的引用
     */
    private val paint: Paint by lazy { Paint() }
    /**
     * 当前进度
     */
    private var progressL: Int = 0
    /**
     * 最大进度
     */
    private var maxL: Int = 100
    /**
     * 中间进度百分比的字符串的颜色
     */
    private var textColor: Int = Color.BLUE
    /**
     * 中间圆的颜色
     */
    private var circleColor: Int = Color.GRAY
    /**
     * 中间进度百分比的字符串的字体
     */
    private var textSize: Float = 15F

    init {
        val mTypedArray = context.obtainStyledAttributes(attrs, R.styleable.NumberProgressBar)
        textColor = mTypedArray.getColor(R.styleable.NumberProgressBar_nTextColor, Color.BLUE)
        textSize = mTypedArray.getDimension(R.styleable.NumberProgressBar_nTextSize, 15f)
        max = mTypedArray.getInteger(R.styleable.NumberProgressBar_nMax, 100)
        circleColor = mTypedArray.getColor(R.styleable.NumberProgressBar_nCircleColor, Color.GRAY)
        mTypedArray.recycle()
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        val centre = (width / 2).toFloat() //获取圆心的x坐标
        val mPadding = centre / 131 * 35//外圈进度条的环的宽度
        paint.strokeWidth = 0f
        paint.color = circleColor
        canvas.drawCircle(centre, centre, centre - mPadding, paint)
        paint.color = textColor
        paint.textSize = textSize
        paint.typeface = Typeface.DEFAULT_BOLD //设置字体
        /*
         * 画进度百分比
         */
        val percent = (progress.toFloat() / max.toFloat() * 100).toInt()  //中间的进度百分比，先转换成float在进行除法运算，不然都为0
        val textWidth = paint.measureText("$percent%")   //测量字体宽度，我们需要根据字体的宽度设置在圆环中间
        canvas.drawText("$percent%", centre - textWidth / 2, centre + textSize / 2, paint) //画出进度百分比
    }

    /**
     * 设置进度，此为线程安全控件，由于考虑多线的问题，需要同步
     * 刷新界面调用postInvalidate()能在非UI线程刷新
     *
     * @param progress
     */
    @Synchronized
    override fun setProgress(progress: Int) {
        var progressCopy = progress
        if (progressCopy < 0) {
            throw IllegalArgumentException("progress not less than 0")
        }
        if (progressCopy > max) {
            progressCopy = max
        }
        if (progressCopy <= max) {
            this.progressL = progressCopy
            postInvalidate()
        }

    }
}